
from ast import alias
from cProfile import label
from functools import reduce
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statistics
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42

sns.set_theme(style="darkgrid")
# sns.set(rc={"figure.figsize": (6, 3.5)})
sns.set(font_scale=1.6)


def opt1():
    x = range(2, 112)
    nosn = []
    notn = []
    osn = []
    otn = []
    rs = []
    rt = []
    for k in x:
        nosn.append(202 * k * 48 * (k-1) * 48 + 6 * k * 48 * 47)
        notn.append(392 * k * 48 * (k-1) * 48 + 8 * k * 48 * 47)
        osn.append((k * 52 + 192) * k * 48)
        otn.append(k * 4 * 96 * k * 48)
        rs.append((26 * k+96)/(4848 * k - 4707))
        rt.append(48 * k/(2352 * k - 2305))

    # plt.bar(x, nosn)
    # plt.bar(x, osn, label="Opt #states")

    plt.plot(x, rs, label='state ratio')
    plt.plot(x, rt, label='trans ratio')

    # plt.yscale('log')
    # plt.plot(x, nosn)
    # plt.plot(x, nosn)
    plt.legend()
    # plt.show()
    plt.savefig('result.png')


def cpu_mem_cdf():
    # 336:28:12 
    n_rsw = 48*112
    n_fsw = 4*112
    n_ssw = 192
    cpu = {'rsw': [], 'fsw': [], 'ssw': []}
    mem = {'rsw': [], 'fsw': [], 'ssw': []}
    bw = []
    time = {'rsw': [], 'fsw': [], 'ssw': []}

    i = 0
    for line in open('output/fb.stat.txt'):
        arr = line.split()
        if i < 40:
            mem['rsw'].append(float(arr[-1])/1000000)
            cpu['rsw'].append(float(arr[-2]) * 100)
            time['rsw'].append(float(arr[-3]) / 1000)
        elif i < 80:
            mem['fsw'].append(float(arr[-1])/1000000)
            cpu['fsw'].append(float(arr[-2]) * 100)
            time['fsw'].append(float(arr[-3]) / 1000)
        elif i < 120:
            mem['ssw'].append(float(arr[-1])/1000000)
            cpu['fsw'].append(float(arr[-2]) * 100)
            time['fsw'].append(float(arr[-3]) / 1000)
        i += 1

    for v in mem.values():
        v.sort()
    for v in cpu.values():
        v.sort()
    for v in time.values():
        v.sort()
    mem['fsw'] = mem['fsw'][0:int(n_fsw/n_rsw)+1]
    mem['ssw'] = mem['ssw'][0:int(n_ssw/n_rsw)+1]
    cpu['fsw'] = cpu['fsw'][0:int(n_fsw/n_rsw)+1]
    cpu['ssw'] = cpu['ssw'][0:int(n_ssw/n_rsw)+1]
    time['fsw'] = time['fsw'][0:int(n_fsw/n_rsw)+1]
    time['ssw'] = time['ssw'][0:int(n_ssw/n_rsw)+1]

    for line in open('envs/fb4/gen/bwstat.txt'):
        arr = line.split()
        bw.append(float(arr[-1]) * 8 / 1000)

    print(min(reduce(lambda x, y: x + y, time.values())))
    print(max(reduce(lambda x, y: x + y, time.values())))
    print(statistics.mean(reduce(lambda x, y: x + y, time.values())))
    df = pd.DataFrame({'Fabric-112': reduce(lambda x, y: x + y, mem.values())})
    f = sns.ecdfplot(data=df)
    # plt.xlabel('Memory(MB)', weight='bold', fontsize=18)
    plt.xlabel('Memory(MB)', weight='bold')
    plt.ylabel('')
    plt.tight_layout()
    plt.savefig('output/mem.pdf')
    # plt.show()
    plt.figure()
    df = pd.DataFrame({'Fabric-112': reduce(lambda x, y: x + y, cpu.values())})
    f = sns.ecdfplot(data=df)
    plt.xlabel('CPU usage(%)', weight='bold')
    plt.ylabel('')
    plt.tight_layout()
    plt.savefig('output/cpu.pdf')
    # plt.show()
    plt.figure()
    df = pd.DataFrame({'Fabric-112': bw})
    f = sns.ecdfplot(data=df)
    plt.xlabel('Bandwidth usage(Kbps)', weight='bold')
    plt.ylabel('')
    plt.tight_layout()
    plt.savefig('output/bw.pdf')

def cpu_net_tl(net):
    devs = ['rsw', 'fsw', 'ssw']
    dev_to_standard = {'rsw': 'ToR', 'fsw': 'Agg', 'ssw': 'Core'}
    cpus = {}
    nets = {}
    mems = {}
    for dev in devs:
        cpus[dev] = []
        nets[dev] = []
        mems[dev] = []
        for line in open('output/top.%s.%s.txt' % (net, dev)):
            if line.strip() == '':
                cpus[dev].append(0)
                mems[dev].append(0)
            else:
                arr = line.split()
                cpus[dev].append(float(arr[8])/8)
                mems[dev].append(int(arr[5])/1000)
            # if 'all' in line and 'Average' not in line:
            #     arr = line.split()
            #     cpus[dev].append(float(arr[3]))
        
        
        for line in open('output/fb/sar.net.%s.%s.txt' % (net, dev)):
            if 'Ethernet1 ' in line and 'Average' not in line:
                arr = line.split()
                nets[dev].append(float(arr[6]))
        for i in range(10):
            nets[dev][i] = 0
    print(nets['fsw'])

    x = range(len(cpus['rsw']))
    
    plt.figure()
    markers = ['+', 'x', '.']
    lst = ['m--', '-', '-']
    for dev in devs:
        plt.plot(x, cpus[dev], lst.pop(), marker=markers.pop(), label=dev_to_standard[dev])
    plt.xlabel('Time (s)', weight='bold')
    plt.ylabel('CPU (%)', weight='bold')
    plt.legend()
    plt.ylim(0, 100)
    # plt.grid(False)
    plt.tight_layout(pad=.1)
    plt.savefig('output/fb/cpu.all.pdf' )

    plt.figure()
    markers = ['+', 'x', '.']
    lst = ['m--', '-', '-']
    for dev in devs:
        plt.plot(x, nets[dev], lst.pop(), marker=markers.pop(), label=dev_to_standard[dev])
    plt.xlabel('Time (s)', weight='bold')
    plt.ylabel('Bandwidth (Kbps)', weight='bold')
    plt.legend()
    # plt.grid(False)
    plt.tight_layout(pad=.1)
    plt.savefig('output/fb/net.all.pdf')

    plt.figure()
    markers = ['+', 'x', '.']
    lst = ['m--', '-', '-']
    for dev in devs:
        plt.plot(x, mems[dev], lst.pop(), marker=markers.pop(), label=dev_to_standard[dev])
    plt.xlabel('Time (s)', weight='bold')
    plt.ylabel('Memory (MB)', weight='bold')
    plt.legend()
    # plt.grid(False)
    plt.tight_layout(pad=.1)
    plt.savefig('output/fb/mem.all.pdf')

    # for dev in devs:
    #     plt.figure()
    #     plt.plot(x, cpus[dev])
    #     plt.xlabel('Time (s)', weight='bold')
    #     plt.ylabel('CPU (%)', weight='bold')
    #     plt.tight_layout()
    #     plt.savefig('output/fb/cpu.%s.pdf' % (dev))

    #     plt.figure()
    #     plt.plot(x, nets[dev])
    #     plt.xlabel('Time (s)', weight='bold')
    #     plt.ylabel('Bandwidth (Kbps)', weight='bold')
    #     plt.tight_layout()
    #     plt.savefig('output/fb/net.%s.pdf' % (dev))


def stat():
    devs = ['rsw', 'fsw', 'ssw']
    vts = {'rsw': [], 'fsw': [], 'ssw': []}
    for dev in devs:
        for line in open('output/ft40/inc.%s.txt' % dev):
            if 'time' not in line:
                continue
            arr = line.split()
            vts[dev].append(int(arr[5]))

    all = reduce(lambda x, y: x + y, vts.values())
    print(min(all))
    print(max(all))
    print(statistics.mean(all))

def stat_wan(net, sys='ddm'):
    vts = []
    if sys == 'ddm':
        for line in open('output/%s/inc.txt' % (net)):
            if 'time' not in line:
                continue
            arr = line.split()
            vts.append(int(arr[5]))
    elif sys == 'atom':
        for line in open('output/%s/inc.%s.txt' % (net, sys)):
            if 'time' not in line:
                continue
            arr = line.split()
            vts.append(int(arr[1]))
    print(min(vts))
    print(max(vts))
    print(statistics.mean(vts))

def plot_dfa_opt():
    df = pd.read_csv('output/dfasize.txt')

    plt.figure(figsize=(8, 4))
    ax = sns.barplot(x='topo', y='data', hue='type', data=df)

    # for i, bar in enumerate(ax.containers):
    #     plt.bar_label(bar, fmt='%.4f')

    plt.xlabel('')
    plt.ylabel('')
    plt.yscale('log')
    ax.legend_.set_title(None)
    plt.tight_layout()
    plt.savefig('output/dfasize.pdf')
    plt.show()

def plot_vt_cdf(net):
    devs = ['rsw', 'fsw', 'ssw']
    di = {'aritel': 1, 'ft40': 4, 'i2': 2, 'fb': 5}
    vts = {'DOME': [], 'B-APKeep': [], 'Delta-Net': []}
    for line in open('output/bapkeep.csv', encoding='utf8'):
        if line[0] != ',':
            continue
        arr = line.split(',')
        vts['B-APKeep'].append(float(arr[di[net]]))

    if net == 'ft40' or net == 'fb':
        for dev in devs:
            devc = {'rsw':40, 'fsw':40, 'ssw':20}
            if net == 'fb':
                devc = {'rsw': 89, 'fsw': 7, 'ssw': 4}
            i = devc[dev]
            for line in open('output/%s/inc.%s.txt' % (net, dev)):
                if 'time' not in line:
                    continue
                arr = line.split()
                vts['DOME'].append(float(arr[5])/1000000)
                i -= 1
                if i == 0:
                    break
        # vts['dome'].append(float(arr[-3]) / 1000000)
    elif net == 'i2':
        for line in open('output/%s/inc.txt' % (net)):
            if 'time' not in line:
                continue
            arr = line.split()
            vts['DOME'].append(float(arr[5])/1000000)
        for line in open('output/%s/inc.atom.txt' % (net)):
            if 'time' not in line:
                continue
            arr = line.split()
            vts['Delta-Net'].append(float(arr[1])/1000000)


    # vts['DOME'].sort()
    data = {}
    for k in vts:
        if len(vts[k]) > 0:
            print(k, min(vts[k]), max(vts[k]), statistics.mean(vts[k]))
            data[k] = vts[k][:100]
    
    
    df = pd.DataFrame(data)
    f = sns.ecdfplot(data=df)
    plt.xlabel('Time (ms)', weight='bold')
    plt.ylabel('')
    # df = pd.DataFrame({'dome': vts['dome']})
    # f = sns.ecdfplot(data=df)
    plt.tight_layout()
    plt.savefig('output/%s/vtcdf-%s.pdf' % (net, net))
    plt.show()

def plot_vt_cdf1():
    data = {
        'DOME (Fabric-112)': [],
        'DOME (FatTree-40)': [], 
        'B-APKeep (Fabric-112)': [], 
        'B-APKeep (FatTree-40)': []
        }
    for line in open('output/bapkeep.csv', encoding='utf8'):
        if line[0] != ',':
            continue
        arr = line.split(',')
        data['B-APKeep (Fabric-112)'].append(float(arr[5]))
        data['B-APKeep (FatTree-40)'].append(float(arr[4]))

    net_to_dir = {'Fabric-112': 'fb', 'FatTree-40': 'ft40'}
    for method in ['DOME', 'B-APKeep']:
        for net in ['Fabric-112', 'FatTree-40']:
            for dev in ['rsw', 'fsw', 'ssw']:
                devc = {'rsw':40, 'fsw':40, 'ssw':20}
                if net == 'Fabric-112':
                    devc = {'rsw': 89, 'fsw': 7, 'ssw': 4}
                i = devc[dev]
                for line in open('output/%s/inc.%s.txt' % (net_to_dir[net], dev)):
                    if 'time' not in line:
                        continue
                    arr = line.split()
                    data['%s (%s)' % (method, net)].append(float(arr[5])/1000000)
                    i -= 1
                    if i == 0:
                        break
    for d in data:
        data[d] = data[d][:100]
    df = pd.DataFrame(data)
    plt.figure(figsize=(9,3.5))
    f = sns.ecdfplot(data=df)
    # plt.legend(fontsize=12)
    # plt.legend(f.get_legend().get_texts(),fontsize='12')
    sns.move_legend(f, bbox_to_anchor=(.8,0), loc="lower left")
    plt.xlabel('Time (ms)', weight='bold')
    plt.ylabel('')
    # df = pd.DataFrame({'dome': vts['dome']})
    # f = sns.ecdfplot(data=df)
    plt.tight_layout(pad=1)
    
    # leg = plt.legend()
    
    plt.savefig('output/vtcdf-all.pdf')
    plt.show()

plot_vt_cdf1()
# plot_vt_cdf('fb')
# plot_dfa_opt()
# stat_wan('airtel', 'atom')
# stat()
# cpu_net_tl('fb')
# cpu_mem_cdf()
